const db = require('../config/db.config.js');

// 获取知识列表
exports.getAllKnowledge = async (req, res) => {
  try {
    const [articles] = await db.query('SELECT * FROM Knowledge');
    res.json(articles);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取单篇文章
exports.getKnowledgeById = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user?.id;

    let query = `
      SELECT k.*, 
        (SELECT COUNT(*) FROM Likes WHERE content_id = k.id AND content_type = 'knowledge') as likes_count,
        (SELECT COUNT(*) FROM Favorites WHERE content_id = k.id AND content_type = 'knowledge') as favorites_count,
        CASE WHEN EXISTS (
          SELECT 1 FROM Likes 
          WHERE content_id = k.id 
          AND content_type = 'knowledge' 
          AND user_id = ?
        ) THEN true ELSE false END as is_liked,
        CASE WHEN EXISTS (
          SELECT 1 FROM Favorites 
          WHERE content_id = k.id 
          AND content_type = 'knowledge' 
          AND user_id = ?
        ) THEN true ELSE false END as is_favorited
      FROM Knowledge k
      WHERE k.id = ?
    `;

    const [articles] = await db.query(query, [userId, userId, id]);

    if (!articles[0]) {
      return res.status(404).json({ message: '文章不存在' });
    }

    // 生成分享URL
    const shareUrl = `${process.env.FRONTEND_URL}/knowledge/${id}`;
    articles[0].share_url = shareUrl;

    res.json(articles[0]);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 创建文章（管理员权限）
exports.createKnowledge = async (req, res) => {
  try {
    const { title, content } = req.body;

    const [result] = await db.query(
      'INSERT INTO Knowledge (title, content) VALUES (?, ?)',
      [title, content]
    );

    res.status(201).json({
      message: '文章创建成功',
      articleId: result.insertId,
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 更新文章（管理员权限）
exports.updateKnowledge = async (req, res) => {
  try {
    const { id } = req.params;
    const { title, content } = req.body;

    const [result] = await db.query(
      'UPDATE Knowledge SET title = ?, content = ? WHERE id = ?',
      [title, content, id]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({ message: '文章不存在' });
    }

    res.json({ message: '文章更新成功' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 删除文章（管理员权限）
exports.deleteKnowledge = async (req, res) => {
  try {
    const { id } = req.params;

    const [result] = await db.query('DELETE FROM Knowledge WHERE id = ?', [id]);

    if (result.affectedRows === 0) {
      return res.status(404).json({ message: '文章不存在' });
    }

    res.json({ message: '文章删除成功' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 点赞知识文章
exports.likeKnowledge = async (req, res) => {
  const connection = await db.getConnection();
  try {
    await connection.beginTransaction();
    const knowledgeId = req.params.knowledgeId;
    const userId = req.user.id;

    // 检查文章是否存在
    const [knowledge] = await connection.query(
      'SELECT * FROM Knowledge WHERE id = ?',
      [knowledgeId]
    );
    if (knowledge.length === 0) {
      return res.status(404).json({ message: '文章不存在' });
    }

    // 检查是否已经点赞
    const [likes] = await connection.query(
      'SELECT * FROM Likes WHERE user_id = ? AND content_type = ? AND content_id = ?',
      [userId, 'knowledge', knowledgeId]
    );

    if (likes.length > 0) {
      // 取消点赞
      await connection.query(
        'DELETE FROM Likes WHERE user_id = ? AND content_type = ? AND content_id = ?',
        [userId, 'knowledge', knowledgeId]
      );
      await connection.commit();
      return res.json({ message: '操作成功', liked: false });
    }

    // 添加点赞
    await connection.query(
      'INSERT INTO Likes (user_id, content_type, content_id) VALUES (?, ?, ?)',
      [userId, 'knowledge', knowledgeId]
    );

    await connection.commit();
    res.json({ message: '操作成功', liked: true });
  } catch (error) {
    await connection.rollback();
    console.error('点赞失败:', error);
    res.status(500).json({ message: '操作失败' });
  } finally {
    connection.release();
  }
};

// 取消点赞知识文章
exports.unlikeKnowledge = async (req, res) => {
  try {
    const knowledgeId = req.params.knowledgeId;
    const userId = req.user.id;

    await db.query(
      'DELETE FROM Likes WHERE user_id = ? AND content_type = ? AND content_id = ?',
      [userId, 'knowledge', knowledgeId]
    );

    res.json({ message: '操作成功', liked: false });
  } catch (error) {
    console.error('取消点赞失败:', error);
    res.status(500).json({ message: '操作失败' });
  }
};

// 收藏知识文章
exports.favoriteKnowledge = async (req, res) => {
  const connection = await db.getConnection();
  try {
    await connection.beginTransaction();
    const knowledgeId = req.params.knowledgeId;
    const userId = req.user.id;

    // 检查文章是否存在
    const [knowledge] = await connection.query(
      'SELECT * FROM Knowledge WHERE id = ?',
      [knowledgeId]
    );
    if (knowledge.length === 0) {
      return res.status(404).json({ message: '文章不存在' });
    }

    // 检查是否已经收藏
    const [favorites] = await connection.query(
      'SELECT * FROM Favorites WHERE user_id = ? AND content_type = ? AND content_id = ?',
      [userId, 'knowledge', knowledgeId]
    );

    if (favorites.length > 0) {
      // 取消收藏
      await connection.query(
        'DELETE FROM Favorites WHERE user_id = ? AND content_type = ? AND content_id = ?',
        [userId, 'knowledge', knowledgeId]
      );
      await connection.query(
        'UPDATE Knowledge SET favorites_count = favorites_count - 1 WHERE id = ?',
        [knowledgeId]
      );
      await connection.commit();
      return res.json({ message: '操作成功', favorited: false });
    }

    // 添加收藏
    await connection.query(
      'INSERT INTO Favorites (user_id, content_type, content_id) VALUES (?, ?, ?)',
      [userId, 'knowledge', knowledgeId]
    );
    await connection.query(
      'UPDATE Knowledge SET favorites_count = favorites_count + 1 WHERE id = ?',
      [knowledgeId]
    );

    await connection.commit();
    res.json({ message: '操作成功', favorited: true });
  } catch (error) {
    await connection.rollback();
    console.error('操作失败:', error);
    res.status(500).json({ message: '操作失败' });
  } finally {
    connection.release();
  }
};

// 取消收藏知识文章
exports.unfavoriteKnowledge = async (req, res) => {
  try {
    const knowledgeId = req.params.knowledgeId;
    const userId = req.user.id;

    await db.query(
      'DELETE FROM Favorites WHERE user_id = ? AND content_type = ? AND content_id = ?',
      [userId, 'knowledge', knowledgeId]
    );

    res.json({ message: '操作成功', favorited: false });
  } catch (error) {
    console.error('取消收藏失败:', error);
    res.status(500).json({ message: '操作失败' });
  }
};
